//
//  PlaceDetailViewC.m
//  WHSport
//
//  Created by ccjoy-jimneylee on 15/3/31.
//  Copyright (c) 2015年 jimneylee. All rights reserved.
//

#import "PlaceDetailViewC.h"
#import "ReservationViewC.h"
#import "BusinessModel.h"
#import "PlaceEntity.h"
#import "Util.h"
#import "AllEvaluaViewC.h"
#import <UIImageView+AFNetworking.h>
#import <ShareSDK/ShareSDK.h>
#import <MBProgressHUD.h>
#import "UserModel.h"
#import "ReservationC.h"

@interface DateCollectionCell : UICollectionViewCell
@property(nonatomic, weak) IBOutlet UILabel *dayLab;
@property(nonatomic, weak) IBOutlet UILabel *weekLab;
@property(nonatomic, weak) IBOutlet UILabel *numLab;
@end
@implementation DateCollectionCell
@end

@interface TypeCollectionCell : UICollectionViewCell
@property(nonatomic, weak) IBOutlet UILabel *typeLab;
@end
@implementation TypeCollectionCell
@end

@interface ServeCollectionCell : UICollectionViewCell
@property(nonatomic, weak) IBOutlet UILabel *strLab;
@property(nonatomic, weak) IBOutlet UIImageView *imgView;
@end
@implementation ServeCollectionCell
@end

@interface PlaceDetailViewC (){
    NSMutableArray *dateArray;
    NSArray *dataArray;
    NSArray *typeArray;
    NSArray *serveArray;
    NSMutableArray *newArray;
    NSArray *restArray;
    NSArray *contArray;
    NSString *hallNum;
    NSArray *imgArray;
    BOOL where;
    UIBarButtonItem *rightBtn2;
    NSMutableArray *plistArray;
}

@property (nonatomic, copy)NSString *speID;
@property (nonatomic, copy)NSString *sphID;
@end

@implementation PlaceDetailViewC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.placeNum == nil) {
        [self getData];
    }
    
    self.title =@"场馆详情";
    dateArray = [[NSMutableArray alloc] init];
    plistArray = [[NSMutableArray alloc] init];
    newArray = [[NSMutableArray alloc] init];
    _dateCollection.delegate = self;
    _dateCollection.dataSource = self;
    _typeCollection.delegate = self;
    _typeCollection.dataSource = self;
    _serverCollection.delegate = self;
    _serverCollection.dataSource = self;
    [self getSevenDays];
    
    self.scrollView = [[UIScrollView alloc]
                       initWithFrame:
                       CGRectMake(0,
                                  0,
                                  MAIN_SCREEN_SIZE.width,
                                  self.photoView.frame.size.height)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bouncesZoom = NO;
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.photoView addSubview:self.scrollView];
    where = NO;

    UIBarButtonItem *rightBtn1 = [[UIBarButtonItem alloc]
                                 initWithImage:[UIImage imageNamed:@"shareimage"]
                                 style:UIBarButtonItemStylePlain
                                 target:self action:@selector(shareBtn:)];
    rightBtn2 = [[UIBarButtonItem alloc]
                                  initWithImage:[UIImage imageNamed:@"collectimage"]
                                  style:UIBarButtonItemStylePlain
                                  target:self action:@selector(collectionBtn:)];
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:rightBtn1,rightBtn2, nil]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)collectionBtn:(id)sender{
    
    if (rightBtn2.tag == 2 || plistArray.count == 0) {
        NSArray *paths=NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *plistPaht=[paths objectAtIndex:0];
        //取得完整的文件名
        NSString *fileName=[plistPaht stringByAppendingPathComponent:@"Place.plist"];
        NSMutableArray *allArray = [NSMutableArray arrayWithContentsOfFile:fileName];
        [allArray addObjectsFromArray:dataArray];
        //创建并写入文件
        [allArray writeToFile:fileName atomically:YES];
        [rightBtn2 setImage:[UIImage imageNamed:@"fullcollectimage"]];
    }
    
}
- (void)shareBtn:(id)sender{
    
    NSString* path = [[NSBundle mainBundle]pathForResource:@"ShareSDK" ofType:@"png"];
    id<ISSContent> publishContent = [ShareSDK content:@"你好,请填写分享内容!" defaultContent:nil image:[ShareSDK imageWithPath:path] title:@"添加标题" url:@"http://mob.com" description:@"添加描述" mediaType:SSPublishContentMediaTypeNews];
    //2.调用分享菜单分享
    [ShareSDK showShareActionSheet:nil shareList:nil content:publishContent statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        //如果分享成功
        if (state == SSResponseStateSuccess) {
//            NSLog(@"分享成功");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"分享成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        //如果分享失败
        if (state == SSResponseStateFail) {
//            NSLog(@"分享失败,错误码:%ld,错误描述%@",(long)[error errorCode],[error errorDescription]);
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"分享失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        if (state == SSResponseStateCancel){
//            NSLog(@"分享取消");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"分享取消" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    }];
}

- (void) getData{
    
    NSString *sportsid = [NSString stringWithFormat:@"%@",
                          self.currentPlace.ID];
    NSString *slatitude = self.currentPlace.latitude;
    NSString *slongitude = self.currentPlace.longitude;
    
    [[BusinessModel sharedInstance] getPlaceDateWithSprotsHallID:sportsid latitude:slatitude longitude:slongitude getPlaceData:^(id info) {
        NSDictionary *dic = [info copy];
        dataArray = [NSArray arrayWithObject:dic];
        restArray = info[@"yardCount"];
        typeArray = info[@"sportsEvents"];
        contArray = info[@"evaluations"];
        imgArray = info[@"imgList"];
        NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@""];
        NSString *str = [info[@"serviceItem"] stringByTrimmingCharactersInSet:set];
        serveArray = [str componentsSeparatedByString:@","];
        [_dateCollection reloadData];
        [_typeCollection reloadData];
        [_serverCollection reloadData];
        [self selfTableview];
        [self refreshAds];
        NSString *filename= [NSString stringWithFormat:
                             @"%@/Documents/Place.plist",NSHomeDirectory()];
        NSArray *array  = [NSArray arrayWithContentsOfFile:filename];
        plistArray = [NSMutableArray arrayWithArray:array];
        [self tabbuttonstyle];
    }];
    
}


- (void)getSevenDays{
    
    NSDate*nowDate = [NSDate date];
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM月dd日"];
    NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"yyyy-mm-dd"];
    NSDate* theDate;
    for (int i = 0; i<7; i++) {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow:oneDay*i];
        NSString *allDate=[dateFormatter stringFromDate :theDate];
        NSString *allDate1=[dateFormatter1 stringFromDate :theDate];
        NSString *date = [Util weekdayStringFromDate:theDate];
        if ([date isEqualToString:@"Sunday"]) {
            date = @"周日";
        }
        NSDictionary *dic = @{@"date":allDate,@"week":date,@"allday":allDate1};
        [newArray addObject:dic];
    }
    
    for (NSDictionary *dict in newArray) {
        PlaceEntity *plaEty = [[PlaceEntity alloc] initWithAttributes:dict];
        [dateArray addObject:plaEty];
    }
    
}

- (void)selfTableview{
    
    for (NSDictionary *dic in dataArray) {
        PlaceEntity *plaEty = [[PlaceEntity alloc]
                               initWithAttributes:dic];
        _placeLab.text = plaEty.address;
        NSLog(@"%@",plaEty.distance);
        _meterLab.text = [NSString stringWithFormat:@"%@km",plaEty.distance];
        _teleLab.text = [NSString stringWithFormat:@"%@",plaEty.telephone];
        _faciLab.text = plaEty.facilities;
        _priceLab.text = @"";
        _speciaLab.text = plaEty.charact;
        _nameLab.text = plaEty.name;
//        NSString *str = [NSString stringWithFormat:@"%@",plaEty.level];
//        NSString *num =[Util getstrWithstarNum:str];
//        _starImg.image = [UIImage imageNamed:num];
        hallNum = [NSString stringWithFormat:@"%@",plaEty.ID];
        self.sphID = hallNum;
    }
    
    if (contArray.count == 0) {
        _usernameLab.text = @"";
        _userdateLab.text = @"";
        _usestrImg.image = nil;
        _contLab.text = @"";
    }
    
    for (NSDictionary *dic in contArray ){
        PlaceEntity *plaEty = [[PlaceEntity alloc]
                               initWithAttributes:dic];
        _usernameLab.text = [NSString stringWithFormat:@"%@",
                             plaEty.loginName];
        NSString *time = [NSString stringWithFormat:@"%@",
                          plaEty.createtime];
        if ([time isEqualToString:@"<null>"]) {
            _userdateLab.text = @"";
        }
        else{
            _userdateLab.text = time;
        }
        _contLab.text = [NSString stringWithFormat:@"%@",plaEty.content];
        NSString *str = [NSString stringWithFormat:@"%@",plaEty.level];
        NSString *num =[Util getstrWithstarNum:str];
        _usestrImg.image = [UIImage imageNamed:num];
    }
}

- (void)tabbuttonstyle{
    
    NSString *hallID = [[dataArray objectAtIndex:0] objectForKey:@"id"];
    for (int i = 0; i< [plistArray count ]; i++) {
        NSString *placeID = [[plistArray objectAtIndex:i]
                           objectForKey:@"id"];
        if (placeID == hallID) {
            [rightBtn2 setImage:[UIImage imageNamed:@"fullcollectimage"]];
            rightBtn2.tag = 1;
        }
        if (placeID != hallID){
            [rightBtn2 setImage:[UIImage imageNamed:@"collectimage"]];
            rightBtn2.tag = 2;
        }
    }
}

- (void)refreshAds {
    
    self.scrollView.contentSize =
    CGSizeMake(MAIN_SCREEN_SIZE.width * imgArray.count,
               CGRectGetHeight(self.scrollView.frame));
    [self setupScrollViewImages];
    
    [self.photoView bringSubviewToFront:self.backView];
    self.pageControl.numberOfPages = imgArray.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger pageIndex = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
    self.pageControl.currentPage = pageIndex;
}

- (void)setupScrollViewImages {
    [imgArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary *dic = obj;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:
                                  CGRectMake(MAIN_SCREEN_SIZE.width * idx,
                                             0,
                                             MAIN_SCREEN_SIZE.width,
                                             CGRectGetHeight(self.photoView.frame))];
        imageView.contentMode = UIViewContentModeRedraw;
        NSString *imageUrl = [NSString stringWithFormat:@"http://218.93.12.178:8080/hhw-api/%@",dic];
        [imageView setImageWithURL:[NSURL URLWithString:imageUrl]];
        [_scrollView addSubview:imageView];
    }];
}


- (IBAction)allContBtn:(id)sender{
    if (contArray.count != 0) {
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                       bundle:nil];
        AllEvaluaViewC *allvc = [main instantiateViewControllerWithIdentifier:@"AllEvaluaViewC"];
        allvc.idNum = hallNum;
        [self.navigationController pushViewController:allvc animated:YES];
    }
    else{
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.labelText = @"没有数据";
        [HUD hide:YES afterDelay:1.5f];
    }
}

-(IBAction)phoneBtnAction:(id)sender{
    
    NSString *str = [[dataArray objectAtIndex:0] objectForKey:
                     @"tel://telephone"];
    [[UIApplication sharedApplication] openURL:
     [NSURL URLWithString:str]];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _dateCollection) {
        return dateArray.count;
    }
    if (collectionView == _typeCollection) {
        return typeArray.count;
    }
    return serveArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == _dateCollection) {
        DateCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaceDCell" forIndexPath:indexPath];
        PlaceEntity *placeEty = dateArray[indexPath.row];
        cell.dayLab.text = [NSString stringWithFormat:@"%@",placeEty.day];
        cell.weekLab.text = [NSString stringWithFormat:@"%@",placeEty.week];
        NSString *rest = [NSString stringWithFormat:@"剩余%@",restArray[indexPath.row]];
        if (restArray == nil) {
            rest = @"剩余0";
        }
        cell.numLab.text = rest;
        return cell;
    }
    
    if (collectionView == _typeCollection) {
        TypeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TypeCCell" forIndexPath:indexPath];
        NSString *type = [[typeArray objectAtIndex:indexPath.row] objectForKey:@"event"];
        cell.typeLab.text = type;
        return cell;
    }
    
    else{
        
        ServeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaceSCell" forIndexPath:indexPath];
        NSString *num =[NSString stringWithFormat:@"%@",serveArray[indexPath.row]];
        NSString *img = [Util serviceItem:num];
        cell.imgView.image = [UIImage imageNamed:img];
        NSString *str = [Util serviceStr:num];
        cell.strLab.text = str;
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == _typeCollection) {
        NSString *spid = [[typeArray objectAtIndex:indexPath.row] objectForKey:@"id"];
        self.speID = spid;
    }
    
    if (collectionView == _dateCollection) {
        
        NSString *rest = [NSString stringWithFormat:@"剩余%@",restArray[indexPath.row]];
        if ([rest isEqualToString:@"剩余0"]) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.labelText = @"没有数据";
            [HUD hide:YES afterDelay:1.5f];
        }
        
        else{
    
            if ([UserModel sharedInstance].currentUser == nil) {
                [Util presentLoginControllerFromViewController:self];
            }

            if (self.speID == nil) {
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                HUD.labelText = @"请选择运动项目";
                [HUD hide:YES afterDelay:1.5f];
            }
            
            else{
                PlaceEntity *placeEty = dateArray[indexPath.row];
                NSString *date = [NSString stringWithFormat:@"%@",placeEty.allday];
                UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                               bundle:nil];
                
                ReservationC *con = [main instantiateViewControllerWithIdentifier:@"ReservationC"];
                con.sportEid = self.speID;
                con.sportHid = self.sphID;
                con.time = date;
                [self.navigationController pushViewController:con animated:YES];
                
//                ReservationViewC *resvc = [main instantiateViewControllerWithIdentifier:@"ReservationViewC"];
//                resvc.sportEid = self.speID;
//                resvc.sportHid = self.sphID;
//                resvc.time = date;
//                [self.navigationController pushViewController:resvc animated:YES];
            }
        }
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
}

@end
